package com.py.credit.utils;

import com.alibaba.fastjson.JSONObject;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XmlUtil {

    public static final String SIGN = "5FE965F5FA394762A8B1D06366DBD30D";

    public static final String KEY = "C648D8FDA8FE4595B8F1BFD1F78818BD";

    public static final String HEIMD_KEY = "datatype-负面信息";

    public static final String HONGMD_KEY = "datatype-优良信息";

    public static final String HEIMD_TYPE = "黑名单";

    public static final String HONGMD_TYPE = "红名单";

    public static final String CJ_APPID = "JCQD";

    public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        org.jdom2.Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new ArrayList();
            et = (Element) node.get(i);

            String name = "";
            String tag = "";
            String label = "";

            if (null != et.getAttribute("name") && !et.getAttribute("name").getValue().equals("")) {
                name = "-" + et.getAttribute("name").getValue();
            }
            if (null != et.getAttribute("tag") && !et.getAttribute("tag").getValue().equals("")) {
                tag = "-" + et.getAttribute("tag").getValue();
            }
            if (null != et.getAttribute("label") && !et.getAttribute("label").getValue().equals("")) {
                label = "-" + et.getAttribute("label").getValue();
            }

            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0) {
                    continue;
                }
                if (obj.containsKey(et.getName() + name + tag + label)) {
                    list = (List) obj.get(et.getName() + name + tag + label);
                }
                list.add(iterateElement(et));
                obj.put(et.getName() + name + tag + label, list);
            } else {
                if (obj.containsKey(et.getName() + name + tag + label)) {
                    list = (List) obj.get(et.getName() + name + tag + label);
                }
                list.add(et.getTextTrim());
                obj.put(et.getName() + name + tag + label, list);
            }
        }
        return obj;
    }
}
